package zhihui.mobile.presenter.register;

import android.content.Context;
import android.content.DialogInterface;
import android.content.MutableContextWrapper;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zgm.utils.AppUtils;
import com.zgm.utils.UiUtils;
import com.zgm.utils.WaitUtils;

import org.apache.log4j.Logger;
import org.apache.log4j.varia.FallbackErrorHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import zhihui.mobile.bean.address.BaiduMapInfo;
import zhihui.mobile.bean.address.CommunityInfo;
import zhihui.mobile.bean.address.Location;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.address.AddressManager;
import zhihui.mobile.manager.register.RegisterManager;
import zhihui.mobile.ui.IView;

/**
 * Created by 张公铭 on 2017/7/5 0005.
 */

public class AddressFragmentPresenter implements IAddressFragmentContract.IAddressFragmentPersenter
{
    private Logger logger = Logger.getLogger(AddressFragmentPresenter.class);
    private Context mConetxt;
    private IAddressFragmentContract.IAddressFragmentView addressView;
    private MyLocationListener myLocationListener = new MyLocationListener();
    private AtomicBoolean locationBack = new AtomicBoolean(false);
    private Location curLocation = null;
    private LocationClient mLocationClient;
    public BaiduMapInfo curInfo;

    @Override
    public void init(IView view, Context context)
    {
        mConetxt = context;
        addressView = (IAddressFragmentContract.IAddressFragmentView) view;
    }

    @Override
    public void onResume()
    {
        CommunityInfo curCommunity = RegisterManager.getInstance().getCurCommunityInfo();
        if (curCommunity != null && !TextUtils.isEmpty(curCommunity.getName()))
        {
            addressView.initCommunityEdit(curCommunity.getName());
        } else
        {
            if (addressView.isLocation())
            {
                if (!AppUtils.isOpenGPS(mConetxt))
                {
                    addressView.showLocationDialog();
                } else
                {
                    new LoadLocationTask().execute();
                }
            }

        }
        addressView.showMessage("");
    }

    @Override
    public void saveCommunityId()
    {
        RegisterManager.getInstance().getCurRegister().setCommunityId(Long.parseLong(curInfo.getUid()));
    }

    class LoadLocationTask extends AsyncTask<Void, Void, Boolean>
    {
        @Override
        protected void onPreExecute()
        {
            addressView.showLoading();
        }

        @Override
        protected Boolean doInBackground(Void... params)
        {
            startLocation();
            WaitUtils.Waiting(locationBack, 5 * 1000);
            mLocationClient.stop();
            return locationBack.get();
        }

        @Override
        protected void onPostExecute(Boolean aBoolean)
        {
            if (curLocation != null)
            {
                sendLocation(curLocation);
            } else
            {
                addressView.hindLoading();
                addressView.showMessage("获取定位信息失败，请手动选择小区！");
            }
        }
    }


    private void sendLocation(Location location)
    {
        if (location == null || (location.getLatitude() >= 0 && location.getLongitude() <= 0))
        {
            addressView.hindLoading();
            addressView.showMessage("获取定位信息失败，请手动选择小区！");
            return;
        }

        AddressManager.getInstance().getAddress(location, new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                addressView.hindLoading();
                try
                {
                    String status = result.getString("status");
                    if ("0".equals(status))
                    {
                        JSONArray array = result.getJSONArray("contents");
                        Gson gson = new Gson();
                        List<BaiduMapInfo> list = gson.fromJson(array.toString(), new TypeToken<List<BaiduMapInfo>>()
                        {
                        }.getType());
                        if (list != null && list.size() > 0)
                        {
                            curInfo = getNearCommunity(list);
                            addressView.initCommunityEdit(curInfo.getTitle());
                        }
                    } else
                    {
                        String message = result.getString("message");
                        addressView.showMessage(message);
                    }
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    logger.error("sendLocation json error:" + e.getMessage());
                    addressView.showMessage("解析数据错误！");
                }
            }

            @Override
            public void failed(String message)
            {
                addressView.hindLoading();
                addressView.showMessage(message);
            }
        });
    }

    private BaiduMapInfo getNearCommunity(List<BaiduMapInfo> list)
    {
        if (list == null || list.size() == 0)
        {
            return null;
        }
        BaiduMapInfo baiduMapInfo = null;
        for (BaiduMapInfo temp : list)
        {
            if (baiduMapInfo == null)
            {
                baiduMapInfo = temp;
            } else if (temp.getDistance() < baiduMapInfo.getDistance())
            {
                baiduMapInfo = temp;
            }
        }
        return baiduMapInfo;
    }

    /**
     * 开始定位
     */
    private void startLocation()
    {
        locationBack.set(false);
        mLocationClient = new LocationClient(mConetxt);
        mLocationClient.registerLocationListener(myLocationListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(false);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
        //开启定位
        mLocationClient.start();
    }

    class MyLocationListener implements BDLocationListener
    {

        @Override
        public void onReceiveLocation(BDLocation location)
        {
            Log.i("XXXX", "--------------------------------------");
            Log.i("location:", location.toString());
            if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation
                    || location.getLocType() == BDLocation.TypeOffLineLocation)
            {
                curLocation = new Location();
                curLocation.setLatitude(location.getLatitude());
                curLocation.setLongitude(location.getLongitude());
                if (location.getLatitude() == 0 && location.getLongitude() == 0)
                {
                    locationBack.set(true);
                    return;
                }
                locationBack.set(true);
                Log.i("XXXX", "--------------------------------------yes");
            } else
            {
                locationBack.set(true);
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i)
        {
            Log.i("XXXX", "--------------------------------------" + s + "," + i);
        }
    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onPause()
    {

    }

    @Override
    public void onStop()
    {

    }

    @Override
    public void onDestroy()
    {

    }
}
